import axios from 'axios';
import type { AxiosRequestConfig, AxiosResponse } from 'axios';
import { Message, Notification } from '@arco-design/web-vue';
import { clearToken, getToken } from "@/utils/auth";
import { getTenantId } from "@/utils/tenant";
import router from "@/router";

export interface HttpResponse<T = unknown> {
  message: string;
  code: number;
  data: T;
  timestamp: number
}

if (import.meta.env.VITE_API_BASE_URL) {
  axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL;
}
axios.defaults.timeout = 30000

axios.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const token = getToken();
    if (!config.headers) {
      config.headers = {}
    }
    config.headers.tenantId = getTenantId();
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    // do something
    return Promise.reject(error);
  }
);
// add response interceptors
axios.interceptors.response.use(
  (response: AxiosResponse<HttpResponse>) => response.data,
  async (error) => {
    if (error?.response?.status >= 400 && error?.response?.status < 500) {
      Message.error({
        content: error?.response?.data?.message || '请求失败',
        duration: 5000,
      })
    } else if (error?.response?.status >= 500) {
      Notification.error({
        title: '异常',
        content: error?.response?.data?.message || '',
      })
    }
    if ([401, 40100, 40101, 40102, 50301].includes(error?.response?.data?.code)) {
      clearToken()
      if (!(router?.currentRoute?.value?.name === 'login')) {
        await router.push({
          name: 'login'
        })
      }
    }
    return Promise.reject(error)
  }
);
